//
// Created by grainlee on 16/9/22.
//

#include <iostream>
#include <vector>
#include "structure.h"

using namespace std;

int checkReverse(ListNode *&head ,int k){
    while (k--!=0){
        if(head !=NULL)
            head = head->next;
        else
            return 0;
    }
    return 1;

}
void reverse(ListNode *head, ListNode *tail){
    ListNode *next,*pre,*cur;
    pre = head;
    cur = head->next;
    while (cur !=tail){
        next = cur->next;
        pre->next = next;
        cur ->next = pre;
        pre = cur;
        cur = next;
    }


}
ListNode* reverseKGroup(ListNode* head, int k) {
    if (head == NULL){return NULL;}
    ListNode *tmp = new ListNode(0);
    tmp->next = head;
    ListNode *next = head;
    ListNode *cur = tmp;
    ListNode *tail = head;
    head = tmp;
    while(checkReverse(tail,k)){
        reverse(head->next,tail);
        head = tail;
    }
    return tmp->next;
}

int main(){

    ListNode *head = new ListNode(1);
    ListNode *cur = head;
    for(int i = 2 ;i <= 5; i++){
        ListNode *tmp = new ListNode(i);
        head->next = tmp;
        head = head->next;
    }
    head = reverseKGroup(cur,2);
    while (head != NULL){
        cout << head->val << " ";
        head = head->next;
    }
    char *p = "what dsads";
    p[4] = 0x0;
    cout << p;
    return 0;

}